<template>
  <div class="container">
    <!-- logo -->
    <BrandLogo />

    <!-- 邮箱输入区 -->
    <div class="input-group">
      <label class="input-label">Email</label>
      <input :value="email" class="text-input" placeholder="Please enter the email" disabled />
      <div class="input-tip">An unregistered email will automatically create an account</div>
    </div>

    <!-- 验证码区 -->
    <div class="input-group">
      <div class="code-input-label-group">
        <label class="input-label">Verification Code</label>
        <div class="help-icon" @click="toggleTooltip()">?
          <div id="tooltip" class="tooltip">1. Due to different email filtering rules, the verification code sent to you
            may be in the spam folder
            <br>2. If you encounter any issues receiving the verification code, please contact: support@nearhub.us
          </div>
        </div>
      </div>
      <div class="code-row">
        <input v-model="verificationCode" class="text-input code-input"
          placeholder="Please enter the verification code" />
        <button class="send-btn" @click="sendVerificationCode" :disabled="cooldown > 0">
          {{ cooldown > 0 ? `${cooldown}s` : 'Send' }}
        </button>
      </div>
      <div class="input-tip">The verification code may be in the spam folder</div>
    </div>

    <!-- 注册按钮 -->
    <button class="submit-btn" @click="login">
      <span class="btn-text">Register / Log In</span>
    </button>

    <!-- 协议条款 -->
    <div class="agreement">
      <label class="circle-checkbox">
        <input type="checkbox" v-model="agreedToTerms" />
        <span class="checkmark"></span>
      </label>
      <span class="agreement-text">
        Please read and agree to the
        <router-link to="/user-agreement" class="link">User Agreement</router-link> and
        <router-link to="/privacy-policy" class="link">Privacy Policy</router-link>
      </span>
    </div>

    <!-- Toast 组件 -->
    <AppToast :message="toastMessage" :show="showToastMessage" />
  </div>
</template>

<script>
import BrandLogo from '@/components/BrandLogo.vue';
import AppToast from '@/components/Toast.vue';  // 更新导入名称
import ConstApi from '@/config/api.js'; // 导入API配置

export default {
  components: {
    BrandLogo,
    AppToast  // 更新组件注册名称
  },
  data() {
    return {
      emailRegex: /^[^\s@]+@[^\s@]+\.[^\s@]+/,
      email: localStorage.getItem('userEmail') || '', // 从本地存储获取偏好设置
      verificationCode: '',
      cooldown: 0,
      timer: null,
      agreedToTerms: false,
      preferences: {
        frameName: '',
        inviter: ''
      },
      // 添加 Toast 相关数据
      toastMessage: '',
      showToastMessage: false,
      toastTimer: null
    }
  },
  created() {
    // 首先从 localStorage 读取已保存的 preferences
    const savedPreferences = localStorage.getItem('preferences');
    if (savedPreferences) {
      this.preferences = JSON.parse(savedPreferences);
    }

    // 从路由参数获取并存储到本地存储
    const { email, teamCode, frameName, inviter, departmentPath } = this.$route.query;
    if (email) localStorage.setItem('userEmail', email);
    if (teamCode) localStorage.setItem('teamCode', teamCode);
    if (departmentPath) localStorage.setItem('departmentPath', departmentPath);

    // 只在参数存在时更新 preferences
    if (frameName) this.preferences.frameName = frameName;
    if (inviter) this.preferences.inviter = inviter;

    // 保存到 localStorage
    localStorage.setItem('preferences', JSON.stringify(this.preferences));

    // 更新当前页面的 email
    this.email = localStorage.getItem('userEmail') || '';
  },
  methods: {
    async login() {
      if (!this.verificationCode.trim()) {
        this.showToast('Please enter the verification code');
        return;
      }

      if (!this.agreedToTerms) {
        this.showToast('Please read and agree to the User Agreement and Privacy Policy');
        return;
      }

      try {
        const response = await fetch(ConstApi.baseUrl + ConstApi.login, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            code: this.verificationCode,
            recipient: this.email
          })
        });

        const data = await response.json();

        if (data.code === "0" && data.msg === "success") {
          this.showToast("Log in successful");
          // 将token存储到localStorage
          localStorage.setItem('token', data.data);
          // 延迟跳转，让用户看到成功提示
          setTimeout(() => {
            // 跳转到邀请页面
            this.$router.push({
              path: '/invite-page',
            });
          }, 1500);
        } else {
          this.showToast("Log in failed, please try again later");
        }
      } catch (error) {
        console.error('Login error:', error);
        this.showToast("Log in failed, please try again later");
      }
    },
    toggleTooltip() {
      const tooltip = document.getElementById('tooltip');
      tooltip.classList.toggle('show');
    },
    async sendVerificationCode() {
      // 移除邮箱校验（因邮箱不可编辑且已从本地存储获取）
      if (this.cooldown > 0) {
        return;
      }

      // 直接进入冷却状态
      this.cooldown = 1;

      try {
        // 立即开始倒计时
        this.startCooldown();

        const response = await fetch(ConstApi.baseUrl + ConstApi.sendLoginCode, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            source: 5,
            type: 0,
            recipient: this.email,
            language: 'en'
          })
        });

        const data = await response.json();

        if (data.msg === "success") {
          this.showToast('Verification code has been sent');
        } else {
          clearInterval(this.timer);
          this.timer = null;
          this.cooldown = 0;
          this.showToast('Sending failed, please try again later');
        }
      } catch (error) {
        clearInterval(this.timer);
        this.timer = null;
        this.cooldown = 0;
        console.error('Error sending verification code:', error);
        this.showToast('Sending failed, please try again later');
      }
    },
    startCooldown() {
      if (this.timer) clearInterval(this.timer);

      this.cooldown = 60;
      this.timer = setInterval(() => {
        if (this.cooldown <= 1) {
          clearInterval(this.timer);
          this.timer = null;
          this.cooldown = 0;
        } else {
          this.cooldown--;
        }
      }, 1000);
    },
    showToast(message) {
      this.toastMessage = message;
      this.showToastMessage = true;

      setTimeout(() => {
        this.showToastMessage = false;
        setTimeout(() => {
          this.toastMessage = '';
        }, 400);
      }, 3000);
    }
  },
  beforeUnmount() {
    if (this.timer) {
      clearInterval(this.timer);
    }

    // 清除 toast 定时器
    if (this.toastTimer) {
      clearTimeout(this.toastTimer);
    }
  }
};
</script>

<style scoped>
/* 基础容器 */
.container {
  max-width: 500px;
  padding: 0 20px;
  margin: 20px auto;
  box-sizing: border-box;
}

.input-tip {
  overflow-wrap: break-word;
  color: rgba(166, 166, 166, 1);
  font-size: 14px;
  font-family: Helvetica;
  font-weight: normal;
  text-align: left;
  white-space: normal;
  /* 设置为默认换行方式 */
  line-height: 18px;
  width: 100%;
  word-break: break-word;
  /* 处理长单词/URL换行 */
  margin-top: 5px;
}

/* 导航栏样式 */
.logo {
  font-family: HelveticaNeue-Medium;
  font-size: 25px;
  line-height: 1.2;
}

.brand {
  color: #333;
}

.brand-accent {
  color: #8A69D4;
}

/* 品牌图片 */
.logo-image {
  display: block;
  width: 180px;
  height: auto;
  margin: 30px auto;
  padding-right: 90px;
}

/* 输入组样式 */
.input-group {
  margin: 20px 0;
}

.input-label {
  display: block;
  color: #8A69D4;
  font-family: HelveticaNeue-Medium;
  font-size: 16px;
  margin-bottom: 8px;
  text-align: left;
}

.code-input-label-group {
  display: flex;
}

/* 文本输入框 */
.text-input {
  width: 100%;
  padding: 12px;
  background: #EDEDED;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  box-sizing: border-box;
}

.text-input::placeholder {
  color: rgba(166, 166, 166, 1);
}

/* 验证码行 */
.code-row {
  display: flex;
  gap: 10px;
  margin-top: 8px;
}

.code-input {
  flex: 1;
}

/* 发送按钮 */
.send-btn {
  flex-shrink: 0;
  padding: 12px 25px;
  background: transparent;
  color: #8A69D4;
  border: 2px solid #8A69D4;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 15px;
}

/* 新增悬停状态排除禁用情况 */
.send-btn:hover:not(:disabled) {
  background: #8A69D4;
  color: white;
}

/* 修正后的禁用状态（保留唯一定义） */
.send-btn:disabled {
  background: #EDEDED !important;
  color: #999 !important;
  border-color: #CCC !important;
  cursor: not-allowed !important;
  opacity: 0.8;
}

/* 在.send-btn:disabled 样式后添加 */
.text-input:disabled {
  background: #EDEDED;
  color: #666;
  cursor: not-allowed;
}

/* 注册按钮 */
.submit-btn {
  width: 100%;
  padding: 15px;
  background: #8A69D4;
  color: white;
  border: none;
  border-radius: 8px;
  margin-top: 40px;
  font-size: 18px;
  cursor: pointer;
  transition: opacity 0.3s;
}

.submit-btn:hover {
  opacity: 0.9;
}

/* 协议条款 */
.agreement {
  display: flex;
  align-items: center;
  margin-top: 25px;
  font-size: 14px;
  color: #A6A6A6;
  text-align: left;
}

.link {
  color: #8A69D4;
  text-decoration: none;
  cursor: pointer;
}

/* 自定义复选框 */
.circle-checkbox {
  position: relative;
  display: inline-block;
  margin-right: 8px;
  cursor: pointer;
}

.checkmark {
  display: block;
  width: 16px;
  height: 16px;
  border: 2px solid #ccc;
  border-radius: 50%;
  transition: all 0.3s;
}

input[type="checkbox"] {
  position: absolute;
  opacity: 0;
}

input[type="checkbox"]:checked~.checkmark {
  background: #8A69D4;
  border-color: #8A69D4;
}

.checkmark:after {
  content: "";
  position: absolute;
  left: 7px;
  top: 4px;
  width: 4px;
  height: 8px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
  opacity: 0;
}

input[type="checkbox"]:checked~.checkmark:after {
  opacity: 1;
}

/* 响应式处理 */
@media (max-width: 300px) {
  .container {
    padding: 15px;
  }

  .code-row {
    flex-wrap: wrap;
  }

  .send-btn {
    width: 100%;
  }

  .logo-image {
    margin: 20px auto;
  }

  .submit-btn {
    margin-top: 30px;
    padding: 12px;
  }
}

.help-icon {
  position: relative;
  cursor: pointer;
  width: 15px;
  height: 15px;
  border: 1px solid #ccc;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #666;
  margin-left: 5px;
}

.tooltip {
  display: none;
  position: absolute;
  left: calc(100% + 10px);
  /* 调整为右侧显示 */
  top: 50%;
  transform: translateY(-50%);
  z-index: 9999;
  /* 添加最高层级 */
  background: #f8f8f8;
  border: 1px solid #ddd;
  padding: 10px;
  border-radius: 4px;
  min-width: 170px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  font-size: 11px;
  color: #333;
  text-align: left;
}

.tooltip.show {
  display: block;
}

/* 更新Toast样式 */
.toast {
  position: fixed;
  top: 30px;
  left: 50%;
  transform: translateX(-50%) translateY(-100px);
  background-color: #8A69D4;
  color: white;
  padding: 16px 30px;
  border-radius: 25px;
  z-index: 1000;
  transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  font-size: 14px;
  box-shadow: 0 4px 15px rgba(138, 105, 212, 0.3);
  max-width: 80%;
  min-width: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  /* 添加水平居中 */
  text-align: center;
  gap: 10px;
}

.toast.show {
  transform: translateX(-50%) translateY(0);
  animation: toast-bounce 0.6s;
  /* 添加弹性动画 */
}

@keyframes toast-bounce {
  0% {
    transform: translateX(-50%) translateY(-100px);
  }

  50% {
    transform: translateX(-50%) translateY(10px);
  }

  70% {
    transform: translateX(-50%) translateY(-5px);
  }

  100% {
    transform: translateX(-50%) translateY(0);
  }
}

/* 响应式调整 */
@media (max-width: 480px) {
  .toast {
    width: 90%;
    top: 20px;
    padding: 12px 20px;
  }
}
</style>